package com.example.stream;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class TradeDemo {


    public static void main(String[] args) {
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario","Milan");
        Trader alan = new Trader("Alan","Cambridge");
        Trader brian = new Trader("Brian","Cambridge");
        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );
        //找出2011年发生的所有交易，并按交易额排序（从低到高）。
        transactions.stream().filter(transaction -> transaction.getYear() == 2011).sorted(Comparator.comparing(Transaction::getValue)).forEach(System.out::println);
        System.out.println("==================");
        //交易员都在哪些不同的城市工作过？
        transactions.stream().map(transaction -> transaction.getTrader().getCity()).distinct().forEach(System.out::println);
        System.out.println("==================");
        //查找所有来自于剑桥的交易员，并按姓名排序。
        transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Cambridge")).map(Transaction::getTrader).sorted(Comparator.comparing(Trader::getName)).forEach(System.out::println);
        System.out.println("==================");
        //(4) 返回所有交易员的姓名字符串，按字母顺序排序。
        String reduce = transactions.stream().map(transaction -> transaction.getTrader().getName()).sorted().reduce("", String::concat);
        System.out.println(reduce);
        System.out.println("==================");
        //(5) 有没有交易员是在米兰工作的？
        boolean milan = transactions.stream().anyMatch(transaction -> transaction.getTrader().getCity().equals("Milan"));
        System.out.println(milan);
        System.out.println("==================");
        //(6) 打印生活在剑桥的交易员的所有交易额。
        Integer cambridge = transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Cambridge")).map(Transaction::getValue).reduce(0, Integer::sum);
        System.out.println(cambridge);
        System.out.println("==================");
        //(7) 所有交易中，最高的交易额是多少？
        Optional<Integer> max = transactions.stream().map(Transaction::getValue).max(Integer::compareTo);
        System.out.println(max.get());
        System.out.println("==================");
        //(8) 找到交易额最小的交易。
        Optional<Transaction> min = transactions.stream().min(Comparator.comparing(Transaction::getValue));
        System.out.println(min.get());
    }
}
